<template>
  <div class="headBack">
    <router-link class="goback" to="/" v-if="isDetail">返回</router-link>
    <el-menu
      v-else
      :default-active="'/'"
      class="el-menu-demo"
      mode="horizontal"
      background-color="#282a2c00"
      text-color="#fff"
      active-text-color="#ffd04b"
      popper-effect="dark"
      @select="handleSelect"
    >
      <el-menu-item index="/">首页</el-menu-item>
      <el-sub-menu index="2">
        <template #title>分类</template>
        <el-menu-item v-for="item in classList" :key="item.id" @click="handleChange(item)">
          {{ item.name }}
        </el-menu-item>
      </el-sub-menu>
      <!-- <el-menu-item index="3">友链</el-menu-item> -->
      <el-menu-item index="/pictureWall">照片墙</el-menu-item>
    </el-menu>
    <div class="login-box">
      <template v-if="!isLogin">
        <div @click="showLogin(true)">登录</div>
        <span>|</span>
        <div @click="showRegister(true)">注册</div>
      </template>
      <template v-else>
        <img :src="userInfo.avatar" alt="" class="user-avatar" />
        <el-dropdown>
          <span class="nick-name">{{ userInfo.nickName }}</span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="showPersonalCenter">个人中心</el-dropdown-item>
              <el-dropdown-item @click="handleLogOut">退出</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
      <div class="item">
        <svg-icon
          style="cursor: pointer"
          size="20px"
          :icon-class="isDark ? 'moon' : 'sun'"
          @click="toggle()"
        ></svg-icon>
      </div>
      <div class="item">
        <svg-icon
          style="cursor: pointer"
          size="20px"
          :icon-class="!ispink ? 'blue' : 'pink'"
          @click="changeStyle"
        ></svg-icon>
      </div>
    </div>
  </div>
  <Login @show-login="showLogin" @show-register="showRegister" :isShowLogin="isShowLogin" />
  <Register @show-register="showRegister" @show-login="showLogin" :isShowRegister="isShowRegister" />
</template>

<script setup>
import { getCategoryList } from '@/api/category';
import { logout } from '@/api/user';
import SvgIcon from '@/components/svgIcon/index.vue';
import Login from '@/pages/components/login/index.vue';
import Register from '@/pages/components/register/index.vue';
import { useArticleStore } from '@/store/article';
import { useUsersStore } from '@/store/user';
import { removeToken } from '@/utils/auth';
import { getStory, setStory } from '@/utils/local';
import { useDark, useToggle } from '@vueuse/core';
import { ElMessage, ElMessageBox } from 'element-plus';
import { storeToRefs } from 'pinia';
import { onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();
const { userInfo } = storeToRefs(useUsersStore());
const { setUserInfo: setUserStore } = useUsersStore();

const { setArticleType } = useArticleStore();

const props = defineProps({
  isDetail: {
    type: Boolean,
    default: false,
  },
});

const isDark = useDark({
  selector: 'html',
  attribute: 'theme',
  valueDark: 'dark',
  valueLight: 'light',
});

const toggle = useToggle(isDark);

onMounted(() => {
  !props.isDetail && queryCategoryList();
});
const classList = ref([]); // 分类数据
const handleSelect = (key, keyPath) => {
  console.log(key, keyPath);
  router.push(key);
};

// 点击分类
const handleChange = (item) => {
  setArticleType(item.id);
};

// 获取分类数据
const queryCategoryList = async () => {
  const res = await getCategoryList();
  if (res.code === 200) {
    classList.value = [
      {
        id: '',
        name: '全部',
      },
      ...res.data,
    ];
  }
};

// 退出接口
const beforeClose = async (action, instance, done) => {
  if (action === 'confirm') {
    const res = await logout();
    if (res.code === 200) {
      removeToken();
      ElMessage({
        type: 'success',
        message: '退出成功',
      });
      setUserStore({});
      done();
    }
  } else {
    done();
  }
};

// 登录功能
const isShowLogin = ref(false);
const showLogin = (val) => {
  isShowLogin.value = val;
};

// 退出登录
const handleLogOut = () => {
  ElMessageBox.confirm('确认退出码?', '退出', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    beforeClose: beforeClose,
  });
};

// 注册功能
const isShowRegister = ref(false);
const showRegister = (val) => {
  isShowRegister.value = val;
};

// 跳转个人中心
const showPersonalCenter = () => {
  router.push('/personalCenter');
};

// 动态导入SCSS文件的函数
const importScss = (filename) => {
  return new Promise((resolve, reject) => {
    const fullPath = `/styles/${filename}.css`;
    const link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.href = fullPath;
    link.id = 'styleId';

    link.onload = () => resolve();
    link.onerror = () => reject(new Error(`Could not load ${fullPath}`));
    document.head.appendChild(link);
    setStory('styleName', filename);
  });
};

const scssFileName = ref('theme-blue');
const ispink = ref(true);
const changeStyle = () => {
  const linkTag = document.getElementById('styleId');
  if (linkTag) {
    linkTag.parentNode.removeChild(linkTag);
  }
  ispink.value = !ispink.value;
  scssFileName.value = ispink.value ? 'theme-shoka' : 'theme-blue';
  importScss(scssFileName.value);
};

onMounted(() => {
  const styleName = getStory('styleName');
  ispink.value = styleName === 'theme-shoka' ? true : false;
  importScss(styleName || scssFileName.value);
});

// 是否已经登录
const isLogin = ref(false);
watch(
  userInfo,
  (newValue, oldValue) => {
    if (newValue.id) {
      isLogin.value = true;
    } else {
      isLogin.value = false;
    }
  },
  {
    immediate: true,
  },
);
</script>
<style lang="scss" scoped>
.headBack {
  width: 100%;
  background: rgb(40 42 44 / 60%);
  box-shadow:
    0 2px 4px 0 rgb(0 0 0 / 12%),
    0 0 6px 0 rgb(0 0 0 / 4%);
  position: fixed;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  background-image: radial-gradient(transparent 1px, #79747445 1px);
  background-size: 4px 4px;
  backdrop-filter: saturate(50%) blur(4px);
  top: 0;

  .goback {
    padding: 0 110px;
    height: 60px;
    line-height: 60px;
    color: #fff !important;
  }

  .el-menu-demo {
    padding: 0 100px;
    flex: 1;
  }

  .el-menu--horizontal.el-menu {
    border: none;
  }

  .login-box {
    min-width: 300px;
    display: flex;
    align-items: center;
    color: #fff;
    margin-right: 70px;

    div {
      padding: 0 20px;
      cursor: pointer;
      border: none;
      font-size: 16px;
    }
  }

  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin-right: 10px;
  }

  .nick-name {
    color: #fff;
  }
}
</style>
